package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.TransTypeEnum;
import com.atguigu.srb.core.exception.Assert;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.pojo.entity.UserBind;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.result.ResponseEnum;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.service.UserBindService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.core.utils.LendNoUtils;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.rabbitutil.dto.SmsDTO;
import com.atguigu.srb.rabbitutil.service.MQService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author AtLong
 * @since 2022-06-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TransFlowService transFlowService;
    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private MQService mqService;
    @Resource
    private UserBindService userBindService;
    @Resource
    private   UserAccountService  userAccountService;

    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {
        // 查询用户信息
        UserInfo userInfo = userInfoService.getById(userId);
        String bindCode = userInfo.getBindCode();
        // 判断绑定状态
        Assert.notEmpty(bindCode, ResponseEnum.USER_NO_BIND_ERROR);
        // 生成表单
        // 生成动态表单字符串
        String url = HfbConst.RECHARGE_URL; // 联调地址
        Map<String, Object> map = new HashMap<>();
        map.put("agentId", HfbConst.AGENT_ID); // 给商户分配的唯一标识
        map.put("agentBillNo", LendNoUtils.getChargeNo()); // 商户充值单号
        map.put("bindCode", bindCode); // 充值人绑定协议号
        map.put("chargeAmt", chargeAmt); // 充值金额，即充值到汇付宝的金额。支持小数点后2位。
        map.put("feeAmt", new BigDecimal(0)); // 商户收取用户的手续费。支持小数点后2位。可以传0。
        map.put("returnUrl", HfbConst.RECHARGE_RETURN_URL); // 通知商户充值成功的完整地址
        map.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL); // 充值完成后同步返回商户的完整地址。
        map.put("timestamp", RequestHelper.getTimestamp()); // 时间戳。
        map.put("sign", RequestHelper.getSign(map));  // 验签参数
        // 调用工具类构建方法
        String formStr = FormHelper.buildForm(url, map);
        return formStr;
    }

    // 账户充值异步回调实现异步回调
    //（1）账户金额更改
    //（2）添加交易流水
    @Override
    public String notifyUserAccount(Map<String, Object> paramMap) {
        // 获取参数
        String bindCode = (String) paramMap.get("bindCode");
        String chargeAmt = (String) paramMap.get("chargeAmt");
        String agentBillNo = (String) paramMap.get("agentBillNo");//商户充值订单号
        //判断交易流水是否存在
        boolean isSave = transFlowService.isSaveTransFlow(agentBillNo);
        if (isSave) {
            log.warn("幂等性返回");
            return "fail";
        }

        //（1）账户金额更改user_account
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("bind_code", bindCode);
        UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);
        //查询UserAccount
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id", userInfo.getId());
        UserAccount userAccount = userAccountMapper.selectOne(userAccountQueryWrapper);
        userAccount.setAmount(userAccount.getAmount().add(new BigDecimal(chargeAmt)));
        userAccount.setFreezeAmount(userAccount.getFreezeAmount().add(new BigDecimal(0)));

        // 更新数据
        userAccountMapper.updateById(userAccount);
        //（2）添加交易流水trans_flow
        TransFlow transFlow = new TransFlow();
        transFlow.setMemo("账户充值");
        transFlow.setTransAmount(new BigDecimal(chargeAmt));
        transFlow.setTransNo(agentBillNo);
        transFlow.setTransType(TransTypeEnum.RECHARGE.getTransType());
        transFlow.setTransTypeName(TransTypeEnum.RECHARGE.getTransTypeName());
        transFlow.setUserName(userInfo.getName());
        transFlow.setUserId(userInfo.getId());
        // 调用保存方法
        transFlowService.saveOrUpdate(transFlow);

        // (3) 充值成功发送消息
        String mobile = userInfoService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO(mobile,"ok");
        mqService.mqSendMessage(MQConst.EXCHANGE_TOPIC_SMS,MQConst.ROUTING_SMS_ITEM,smsDTO);

        return "success";
    }

    /**
     * 获取账户余额
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getAccount(Long userId) {
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id",userId);
        UserAccount userAccount = userAccountMapper.selectOne(userAccountQueryWrapper);
        BigDecimal amount = userAccount.getAmount();
        log.debug("获取账户余额--->"+amount);
        return amount;
    }

    @Override
    public void updateUserAccountAmountAndFreezeAmount(Map<String, Object> paramMap) {
        // 获取参数请求
        BigDecimal votePrizeAmt = new BigDecimal(paramMap.get("votePrizeAmt") + "");
        String voteBindCode = (String) paramMap.get("voteBindCode");
        BigDecimal voteAmt = new BigDecimal(paramMap.get("voteAmt") + "");
        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("bind_code", voteBindCode);
        UserBind voteUserBind = userBindService.getOne(userBindQueryWrapper);
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id", voteUserBind.getUserId());
        UserAccount userAccount = userAccountService.getOne(userAccountQueryWrapper);
        userAccount.setAmount(userAccount.getAmount().add(new BigDecimal("-" + voteAmt)).add(votePrizeAmt));
        userAccount.setFreezeAmount(userAccount.getFreezeAmount().add(voteAmt));
        userAccountMapper.updateById(userAccount);

    }

}
